// pages/category/index.js
import { getCategoryList } from '../../request/category'
Page({
  data: {
    leftCategoryList: [],
    rightCategoryList: [],
    currentIndex: 0, //点击选中的菜单项
    scrollTop: 0, //设置右侧回顶
  },
  categoryList: [],
  onLoad: function (options) {
    const categoryList = wx.getStorageSync('categoryList')
    if (!categoryList) {
      this.getCategoryList()
    } else {
      if (Date.now() - categoryList.time > 1000 * 30) {
        this.getCategoryList()
      } else {
        this.categoryList = categoryList.data
        let leftCategoryList = this.categoryList.map(value => value.cat_name)
        let rightCategoryList = this.categoryList[0].children
        this.setData({
          leftCategoryList,
          rightCategoryList
        })
      }
    }
  },

  //获取数据
  async getCategoryList() {
    let categoryListInfo = await getCategoryList()
    this.categoryList = categoryListInfo
    //接口数据存入本地
    wx.setStorageSync("categoryList",{time:Date.now(),data:this.categoryList})
    let leftCategoryList = this.categoryList.map(value => value.cat_name)
    let rightCategoryList = this.categoryList[0].children
    this.setData({
      leftCategoryList,
      rightCategoryList
    })
  },

  //点击事件
  handleItemtap(e) {
    const { index } = e.currentTarget.dataset
    let rightCategoryList = this.categoryList[index].children
    this.setData({
      currentIndex: index,
      rightCategoryList,
      scrollTop: 0
    })
  },
})